package com.cn.demo4.servlet.admin.product;

import com.alibaba.fastjson.JSONObject;
import com.cn.demo4.model.ProductModel;
import com.cn.demo4.service.IProductService;
import com.cn.demo4.service.impl.ProductServiceImpl;
import com.cn.demo4.util.LoadImg;
import com.cn.demo4.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/adminFile/product/update")
public class ProductUpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //2.取得前台传递的值
        LoadImg.loadImg(req);
        /**
         * req在文件流的时候只能拿到一次数据，所以也不能进入过滤器
         */
        //如果没有登录则直接返回resp.getWriter().println(jsonObject);
        HttpSession session = req.getSession();
        String key = (String) req.getAttribute("loginPhone");
        String phone = (String) session.getAttribute(key);
        if (phone == null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", "noLogin");
            resp.getWriter().println(jsonObject);
            return;
        }

        //3.封装数据
        ProductModel productModel = new ProductModel();
        productModel.setId(Tool.stringToInt((String) req.getAttribute("id")));
        productModel.setName((String) req.getAttribute("name"));//参数对应的是前台ajax中data中的属性名
        productModel.setMarketPrice(Tool.stringToDouble((String) req.getAttribute("marketPrice")));
        productModel.setNormalPrice(Tool.stringToDouble((String) req.getAttribute("normalPrice")));
        productModel.setDescription((String) req.getAttribute("description"));
        productModel.setImg((String) req.getAttribute("img"));
//        productModel.setNavImg((String) req.getAttribute("navImg"));
//        productModel.setExample((String) req.getAttribute("example"));
        productModel.setIsShow(Tool.stringToInt((String) req.getAttribute("isShow")));
        productModel.setHouseName((String) req.getAttribute("houseName"));
        productModel.setHouseId(Tool.stringToInt((String) req.getAttribute("houseId")));
        productModel.setCreateTime((String) req.getAttribute("createTime"));
        productModel.setUpdateTime((String) req.getAttribute("updateTime"));
        productModel.setStatus(Tool.stringToInt((String) req.getAttribute("status")));

        //调用服务逻辑层
        IProductService iProductService = new ProductServiceImpl();

        //得到数据
        String result= iProductService.update(productModel);

        //返回结果
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result",result);
        resp.getWriter().println(jsonObject);



    }
}
